<?php

Raise::load('core.ui.RaisePage');

/**
 * RaiseOAuthRequestTokenPage class
 * Step A - B
 *
 * @author Sam-Mauris Yong / hellclanner at live dot com
 * @license http://www.opensource.org/licenses/bsd-license New BSD License
 * @package phpraise.library.oauth.page
 * @since 1.2
 */
abstract class RaiseOAuthRequestTokenPage extends RaisePage{
    
    function __construct() {
        parent::__construct('$output$');
    }

    /**
     * The data store to read/write the data.
     * @var RaiseOAuthDataStore
     */
    private $dataStore;
    
    /**
     * Get or set the data store
     * @param RaiseOAuthDataStore $d (optional) Set the new data store
     * @return RaiseOAuthDataStore
     */
    public function dataStore($d = null){
        if(func_num_args() == 1){
            $this->dataStore = $d;
        }
        return $this->dataStore;
    }
    
    public function build() {
        $auth = $this->application()->request()->headers()->get('Authorization');
        $request = new RaiseOAuthRequestTokenRequest($auth);
        $consumer = $this->dataStore->fetchConsumer($request->consumerKey());
        
        $this->checkSignature($request, $consumer);
        
        $response = $this->dataStore->createRequestToken($request);
        $this->fields()->add('output', $response->response());
    }
    
    private function checkTimestamp($timestamp){
        if((time() - $timestamp) > RaiseOAuth::TIMESTAMP_THRESHOLD){
            throw new Exception();
        }
    }
    
    /**
     *
     * @param RaiseOAuthAccessTokenRequest $request
     * @param RaiseOAuthConsumer $consumer 
     */
    private function checkSignature($request, $consumer){
        // this should probably be in a different method
        $timestamp = $request->timestamp();
        $nonce = $request->nonce();

        $this->checkTimestamp($timestamp);
        if(!$this->dataStore->checkNonce($consumer, $request)){
            throw new Exception();
        }        

        $method = RaiseOAuth::methods()->get($request->signatureMethod());
        if(!$method){
            throw new Exception();
        }
        $signature = new $method($request, $consumer);
        $ok = $signature->check($request->signature());

        if (!$ok) {
          throw new Exception();
        }
    }

    
}
